package me.shurufa.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.LoginActivity;
import me.shurufa.activities.MainActivity;
import me.shurufa.activities.SettingsActivity;
import me.shurufa.net.BaseResponse;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;


public class BaseFragment extends Fragment {

  private static final String LOG_TAG = BaseFragment.class.getSimpleName();

  @Bind(R.id.toolbar)
  @Nullable
  LinearLayout toolbar;

  @Bind(R.id.toolbar_title)
  @Nullable
  TextView titleTextView;

  @Bind(R.id.back)
  @Nullable
  View backInToolbar;

  View rootView;

  @Override
  public void onStart() {
    super.onStart();
  }

  public BaseFragment() {
    // Required empty public constructor
  }

  public void onEventMainThread(Intent intent) {

  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
  }

  @Override
  public void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();

  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_base, container, false);
  }

  @Override
  public void onResume() {
    super.onResume();
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    rootView = view;
    ButterKnife.bind(this, view);
    if (getParentFragment() != null) {
      if (toolbar!=null) {
        toolbar.setVisibility(View.GONE);
      }
    } else {
      if (getActivity() instanceof MainActivity) {
        if (backInToolbar!=null) {
          backInToolbar.setVisibility(View.INVISIBLE);
        }
      } else {
        if (backInToolbar!=null) {
          backInToolbar.setVisibility(View.VISIBLE);
          backInToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().finish();
            }
          });
        }
      }
    }
    initUI(view);
    // 加载缓存
    loadFromCache();
  }

  protected void initUI(View view) {

  }

  protected String cacheKey() {
    return null;
  }

  /**
   * 通过UID+cacheKey获取缓存文件名
   * 
   * @return
   */
  protected String getCacheName() {
    String cacheKey = cacheKey();
    if (TextUtils.isEmpty(cacheKey))
      return null;
    long uid = 0L;
    if (Global.currentUser != null)
      uid = Global.currentUser.uid;
    return uid + "_" + cacheKey;
  }

  protected void loadFromCache() {
    String fileName = getCacheName();
    if (TextUtils.isEmpty(fileName)) {
      return;
    }
    File file = new File(Global.cacheJsonDir, fileName);
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fis);
      String data = Utils.readStream(bis);
      LogUtils.kLog().d(data);
      BaseResponse resp = parseData(data);
      if (resp != null) {
        bindData(resp, false);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LogUtils.d(LOG_TAG, e.getMessage() + e.getCause());
    } finally {
      Utils.closeQuietly(fis);
    }
  }


  /**
   * 解析Json方法需要重写
   * 
   * @param data
   * @return
   */
  protected BaseResponse parseData(String data) {
    return null;
  }

  /**
   * 如果为最新的 且success==true(有data字符串)
   * 写入文件流
   * 
   * @param response
   * @param isNew
   */
  protected void bindData(BaseResponse response, boolean isNew) {
    if (isNew && response.success) {
      String fileName = getCacheName();
      if (!TextUtils.isEmpty(fileName)) {
        File file = new File(Global.cacheJsonDir, fileName);
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
          String data = Global.getGson().toJson(response);
          byte[] bytes = data.getBytes();
          fos = new FileOutputStream(file);
          bos = new BufferedOutputStream(fos);
          bos.write(bytes);
          // notice
          bos.flush();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          Utils.closeQuietly(fos);
          Utils.closeQuietly(bos);
        }
      }
    }
  }

  public void refresh() {}

}
